package com.kedll.library.fragment;

import android.app.Activity;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.bumptech.glide.Glide;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.kedll.library.adapter.MultiTypeAdapter;
import com.kedll.library.mvp.AbstractRefreshPresenter;
import com.kedll.library.util.MyLog;
import com.kedll.library.util.MyUtils;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

import static android.support.v7.widget.RecyclerView.SCROLL_STATE_DRAGGING;
import static android.support.v7.widget.RecyclerView.SCROLL_STATE_SETTLING;

/**
 * 需要上下拉刷新的列表Fragment
 *
 * @author QiQi
 * @date 15/12/18
 */
public abstract class KRefreshListFragment<V extends ViewDataBinding, T extends AbstractRefreshPresenter> extends KRefreshFragment<V, T> implements SwipeMenuRecyclerView.LoadMoreListener {
    public SwipeMenuRecyclerView list;
    protected MultiTypeAdapter adapter;
    private Disposable disposable;

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        list.loadMoreFinish(false, true);
        mPresenter.refreshData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MyUtils.dispose(disposable);
        list.clearOnScrollListeners();
    }

    @Override
    @CallSuper
    protected void init() {
        super.init();
        list = mBinding.getRoot().findViewById(android.R.id.list);
    }

    @Override
    @CallSuper
    protected void initEvent(Bundle savedInstanceState) {
        super.initEvent(savedInstanceState);

        adapter = mPresenter.getAdapter();

        list.setHasFixedSize(false);
        list.setLayoutManager(getLayoutManager());
        List<View> headView = getListHeadView();
        if (headView != null) {
            for (View v : headView) {
                list.addHeaderView(v);
            }
        }
        list.setAdapter(adapter);
        list.setLoadMoreListener(this);


        list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private int mScrollState = -1;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                this.mScrollState = newState;
                if (getContext() == null) {
                    return;
                }
                if (getContext() instanceof Activity) {
                    if (((Activity) getContext()).isDestroyed()) {
                        return;
                    }
                }

                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(getContext()).resumeRequests();
                } else {
                    Glide.with(getContext()).pauseRequests();
                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager != null && layoutManager instanceof FlexboxLayoutManager) {
                    FlexboxLayoutManager staggeredGridLayoutManager = (FlexboxLayoutManager) layoutManager;

                    int itemCount = layoutManager.getItemCount();
                    if (itemCount <= 0) {
                        return;
                    }

                    int lastVisiblePosition = staggeredGridLayoutManager.findLastCompletelyVisibleItemPosition();
                    if (itemCount == lastVisiblePosition + 1 &&
                            (mScrollState == SCROLL_STATE_DRAGGING || mScrollState == SCROLL_STATE_SETTLING)) {
                        onLoadMore();
                    }
                }
            }
        });

    }

    /**
     * 获取布局管理器，默认是纵向线性布局
     * 扩展类可以重写此方法，自定义布局样式
     *
     * @return
     */
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
    }

    protected List<View> getListHeadView() {
        return null;
    }

    @Override
    public void onLoadMore() {
        page++;
        MyUtils.dispose(disposable);
        disposable = Observable.timer(500, TimeUnit.MILLISECONDS)
                .subscribe(aLong -> mPresenter.loadMoreData());

    }

    @Override
    public void loadMoreFinish(boolean emptyData, boolean hasMore) {
        list.loadMoreFinish(emptyData, hasMore);
    }

    @Override
    public void showLoad(String msg) {
        MyLog.getInstance().showProgressDialog(getActivity(), msg);
    }

    @Override
    public void hideLoad() {
        MyLog.getInstance().dismissDialog();
    }
}
